<template>
  <div>
    <!-- 发出方 → 接收方（存在则显示头像+姓名） -->
    <div class="d-flex align-center mb-1 opacity-80">
      <template v-if="fromUser">
        <v-avatar class="mr-1 border-white" size="20">
          <v-img v-if="fromUser.avatar" :alt="fromUser.name" :src="fromUser.avatar" />
          <v-icon v-else :icon="mdiAccount" size="16" />
        </v-avatar>
        <span class="text-caption text-truncate">{{ fromUser.name }}</span>
      </template>
      <template v-else>
        <span class="text-caption text-truncate">{{ note.from || note.user_name }}</span>
      </template>

      <v-icon class="mx-1" :icon="mdiArrowRight" size="14" />

      <template v-if="toUsers && toUsers.length > 0">
        <template v-for="(u, idx) in toUsers.slice(0, 2)" :key="idx">
          <v-avatar class="mr-1 border-white" size="20">
            <v-img v-if="u.avatar" :alt="u.name" :src="u.avatar" />
            <v-icon v-else :icon="mdiAccount" size="16" />
          </v-avatar>
          <span class="text-caption mr-2 text-truncate">{{ u.name }}</span>
        </template>
        <span v-if="toUsers.length > 2" class="text-caption text-medium-emphasis"
          >+{{ toUsers.length - 2 }}</span
        >
      </template>
      <template v-else>
        <span class="text-caption text-truncate">{{ (note.to || []).join(', ') }}</span>
      </template>
    </div>

    <!-- 时间（发送/接收） -->
    <div class="d-flex align-center mb-1 text-caption text-medium-emphasis">
      <v-icon class="mr-1" :icon="mdiClockOutline" size="14" />
      <span>{{ formatDateTime(note.created_at) }}</span>
    </div>

    <!-- 正文两行摘要（解析特殊标记为可点击 Chip） -->
    <div class="message-snippet line-clamp-2 font-weight-regular opacity-80">
      <NoteContentRenderer
        :content="note.content"
        @click-company="handleClickCompany"
        @click-contact="handleClickContact"
        @click-user="handleClickUser"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import NoteContentRenderer from '../common/NoteContentRenderer.vue'
import { mdiAccount, mdiArrowRight, mdiClockOutline } from '@mdi/js'

import type { Note, User } from '../../types'

const props = defineProps<{ note: Note }>()

function fallbackUserFromName(name?: string, idSeed = -1): User | null {
  if (!name) return null
  return { id: idSeed, name }
}

const fromUser = computed<User | null>(() => {
  const u = props.note.from_user
  if (u && u.name) return u
  if (props.note.from && props.note.from.length > 0)
    return { id: -1, name: props.note.from as string }
  // 根据方向回退：外发则从 user，入站则从对方（to_users[0]）
  if (props.note.is_outbound)
    return fallbackUserFromName(props.note.user_name, props.note.user_id ?? -2)
  const toUsers = props.note.to_users

  return toUsers && toUsers[0] ? toUsers[0] : null
})

const toUsers = computed<User[]>(() => {
  const arr = props.note.to_users
  if (arr && arr.length > 0) return arr
  const tos = props.note.to
  if (tos && tos.length > 0) return tos.map((name, idx) => ({ id: -100 - idx, name }))
  // 根据方向回退：入站则我方 user 为接收方；外发则对方（from_user）为接收方
  if (props.note.is_outbound) {
    const fu = props.note.from_user
    return fu ? [{ id: -200, name: fu.name }] : []
  }
  return props.note.user_name ? [{ id: props.note.user_id ?? -3, name: props.note.user_name }] : []
})

// 点击 chips 事件（可由上层接管导航）
function handleClickUser(p: { id: number; name: string }) {
  console.debug('[MessageNote] click-user', p)
}

function handleClickContact(p: { contactId: number; companyId: number; name: string }) {
  console.debug('[MessageNote] click-contact', p)
}
function handleClickCompany(p: { id: number; name: string }) {
  console.debug('[MessageNote] click-company', p)
}

// 格式化日期时间（与普通笔记一致的展示）
function formatDateTime(timestamp: number): string {
  const date = new Date(timestamp)
  return date.toLocaleString()
}
</script>

<style scoped></style>
